/* eslint-disable jsdoc/require-jsdoc */
/* eslint-disable jsdoc/require-description */
/* eslint-disable jsdoc/check-tag-names */
import { ACNormal, PatternsNormal } from '../../common/ac';
import { getStringLength } from '../../common/utils';
let customDict: Record<string, string> = {};

/**
 * @param {{ [key: string]: string }} config - 用户自定义的拼音映射(支持汉字、词语、句子的映射)，若匹配到该映射，优先将汉字转换为该映射
 * @description: 用户自定义拼音
 */
export function customPinyin(config: Record<string, string> = {}) {
  customDict = {};
  const keys = Object.keys(config).sort((key1, key2) => getStringLength(key2) - getStringLength(key1));
  keys.forEach((key) => {
    customDict[key] = config[key]!;
  });
  const customPatterns = Object.keys(customDict).map((key) => ({
    zh: key,
    pinyin: customDict[key],
    priority: 999 + getStringLength(key),
    length: key.length,
  }));
  ACNormal.reset();
  // @ts-expect-error
  ACNormal.buildTrie([...PatternsNormal, ...customPatterns]);
  ACNormal.buildFailPointer();
}

export const getCustomDict = () => {
  return customDict;
};

export function hasCustomConfig() {
  return Boolean(Object.keys(customDict).length);
}
